package com.bw.lib_core.network.interceptor;

import com.bw.lib_core.network.SignUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Iterator;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;


/**
 * 场景：
 * {"name":"tom","pwd":"123123"}
 * sign
 * {"name":"tom","pwd":"123123","sign":"ABC"}
 * <p>
 * 内部定义 tom + 123123 + "abc"  .... -> 不可逆的字符串
 */
public class SignInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        //获取原始请求接口 -> 请求地址，请求方式，请求头 ，请求体
        Request old = chain.request();
        //构建新的对象去修改
        Request.Builder builder = new Request.Builder();
        builder.url(old.url());
        builder.headers(old.headers());
        assert old.body() != null;
        //body中的参数修改
        Buffer buffer = new Buffer();
        old.body().writeTo(buffer);
        String jsonStr = buffer.readUtf8();
        buffer.close();
        //每个参数拿出来,构建新的Body
        RequestBody newBody = null;
        try {
            JSONObject jsonObject = new JSONObject(jsonStr);
            StringBuffer stringBuffer = new StringBuffer();
            //拿出所有values
            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext()) {
                stringBuffer.append(jsonObject.getString(keys.next()));
            }
            String sign = SignUtils.createSign(stringBuffer.toString());
            jsonObject.put("sign", sign);
            newBody = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (newBody == null)
                newBody = old.body();
        }
        builder.post(newBody);
        return chain.proceed(builder.build());
    }
}
